package org.vt.ece4564.pcw.assignment2;

import java.io.IOException;

import java.util.Date;
import java.util.List;

import javax.jdo.Query;

import javax.servlet.ServletConfig;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.vt.ece4564.pcw.assignment2data.Account;
import org.vt.ece4564.pcw.assignment2data.PasswordEncrypt;

@SuppressWarnings("serial")
public class TextInClassLogin extends HttpServlet {
	
	@Override
	public void init(ServletConfig servletConfig) {
		
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		response.setContentType("text/plain");
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String phoneID = request.getParameter("phoneID");
		
		Query query = PMF.get().getPersistenceManager().newQuery("select from " + 
				Account.class.getName() + " where username_==user");
		query.declareParameters("String user");
		
		@SuppressWarnings("unchecked")
		List<Account> accounts = (List<Account>) query.execute(username);
		
		if (accounts == null) {
			response.getWriter().write("Error: Username does not exist");
		}
		
		for (Account a : accounts) {
			if (username.equals(a.getUsername())) {
				String passwordDigest = PasswordEncrypt.encrypt(password);
				
				if (passwordDigest.equals(a.getPasswordDigest())) {
					if (phoneID.equals(a.getPhoneID())) {
						a.incrementLoginCount();
						Date currentDate = new Date();
						Cookie cookie = new Cookie("loggedIn", username + ":" +
								String.valueOf(currentDate.getTime() + 3600*1000) + ":" + 
								String.valueOf(a.getLoginCount()));
					
						response.addCookie(cookie);
						response.getWriter().write("Success");
						return;
					}
					else {
						response.getWriter().write("Error: Different Phone ID");
						return;
					}
				}
				else {
					response.getWriter().write("Error: Incorrect Password");
					return;
				}
			}
		}
		
		response.getWriter().write("Error: Username does not exist");
	}
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws IOException {
		response.sendRedirect("login.html");
	}
}
